using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    private static UIManager instance=new UIManager();
    public static UIManager Instance
    {
        get { return instance; }
    }

    private Dictionary<string, BasePanel> uiDictionary;

    private Transform canvasTrans;

    private UIManager()
    { 
        uiDictionary = new Dictionary<string, BasePanel>();
        canvasTrans = GameObject.Find("Canvas").transform;
        GameObject.DontDestroyOnLoad(canvasTrans.gameObject);
    }

    public T ShowPanel<T>() where T : BasePanel
    {
        string name = typeof(T).Name;

        if (uiDictionary.ContainsKey(name))
        {
            return uiDictionary[name] as T;
        }

        GameObject obj = GameObject.Instantiate(Resources.Load<GameObject>($"UI/{name}"));
        obj.transform.SetParent(canvasTrans, false);

        T panel = obj.GetComponent<T>();

        uiDictionary[name] = panel;

        panel.ShowMe(); 

        return panel; 
    }

    public void HidePanel<T>(bool isFade=true) where T : BasePanel
    {
        string name = typeof(T).Name;

        if (uiDictionary.ContainsKey(name))
        {
            BasePanel panel = uiDictionary[name];
            if (isFade)
            {
                panel.HideMe(() =>
                {
                    GameObject.Destroy(panel.gameObject);
                    uiDictionary.Remove(name);
                });
            }
            else
            {
                GameObject.Destroy(panel.gameObject);
                uiDictionary.Remove(name);
            }
        }
    }

    public T GetPanel<T>() where T : BasePanel
    {
        string name = typeof(T).Name;
        if (uiDictionary.ContainsKey(name))
        { 
            return uiDictionary[name] as T;
        }

        return null;
    }
}
